-- ============================================
-- GUICHET - SNOUB CASINO
-- Identifie le joueur, puis permet de deposer/retirer des Tickets
-- contre des points sur SON solde personnel (via le Serveur Banque).
-- Nécessite : Advanced Computer + Advanced Monitor + Wired Modem
--             + 2 chests (guichet + reserve).
-- ============================================

-- === A CONFIGURER ===
local GUICHET_NAME = "minecraft:chest_2"
local RESERVE_NAME = "minecraft:chest_1"
local CHIP_NAME = "Ticket"
local RATE = 10

local bank = dofile("client_solde.lua")

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end
mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local login = dofile("login.lua")

local guichetChest = peripheral.wrap(GUICHET_NAME)
local reserveChest = peripheral.wrap(RESERVE_NAME)

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local setupError = nil
if not guichetChest then
    setupError = "Chest GUICHET introuvable : " .. GUICHET_NAME
elseif not reserveChest then
    setupError = "Chest RESERVE introuvable : " .. RESERVE_NAME
end

local function isChip(detail)
    return detail ~= nil and detail.displayName == CHIP_NAME
end

local function depositAll(player)
    local converted = 0
    for slot in pairs(guichetChest.list()) do
        local detail = guichetChest.getItemDetail(slot)
        if isChip(detail) then
            local moved = guichetChest.pushItems(RESERVE_NAME, slot, detail.count)
            converted = converted + moved
        end
    end
    if converted > 0 then
        local newBal, err = bank.addBalance(player, converted * RATE)
        return converted, newBal, err
    end
    return 0, nil, nil
end

local function withdraw(player, numChips, currentBalance)
    local cost = numChips * RATE
    if currentBalance < cost then
        return 0, currentBalance, "PAS ASSEZ DE POINTS"
    end

    local remaining = numChips
    for slot in pairs(reserveChest.list()) do
        if remaining <= 0 then break end
        local detail = reserveChest.getItemDetail(slot)
        if isChip(detail) then
            local toMove = math.min(remaining, detail.count)
            local moved = reserveChest.pushItems(GUICHET_NAME, slot, toMove)
            remaining = remaining - moved
        end
    end

    local actuallyMoved = numChips - remaining
    if actuallyMoved <= 0 then
        return 0, currentBalance, "RESERVE VIDE, previens l'admin !"
    end

    local newBal, err = bank.addBalance(player, -(actuallyMoved * RATE))
    if remaining > 0 then
        return actuallyMoved, newBal, "Stock insuffisant, seulement " .. actuallyMoved .. " rendus"
    end
    return actuallyMoved, newBal, nil
end

-- === ECRAN PRINCIPAL DU GUICHET ===
local buttons = {}

local function drawScreen(player, balance, message, msgColor)
    term.setBackgroundColor(colors.black)
    term.clear()
    buttons = {}

    centerText(1, "=== SNOUB CASINO ===", colors.yellow)
    centerText(2, "GUICHET - " .. player, colors.white)
    centerText(4, "Solde : " .. balance .. " points", colors.lime)

    if setupError then
        centerText(6, "ERREUR DE CONFIGURATION", colors.red)
        centerText(7, setupError, colors.red)
        return
    end

    centerText(6, "1 " .. CHIP_NAME .. " = " .. RATE .. " points", colors.lightGray)
    if message then
        centerText(8, message, msgColor or colors.white)
    end

    local labels = {
        { text = "DEPOSER MES TICKETS", action = "deposit" },
        { text = "RETIRER 1 TICKET (" .. RATE .. " pts)", action = "w1" },
        { text = "RETIRER 5 TICKETS (" .. (RATE * 5) .. " pts)", action = "w5" },
        { text = "RETIRER 10 TICKETS (" .. (RATE * 10) .. " pts)", action = "w10" },
        { text = "CHANGER DE JOUEUR", action = "logout" },
    }

    local startY = 10
    for i, btn in ipairs(labels) do
        local bw = #btn.text + 4
        local x1 = math.max(1, math.floor((w - bw) / 2) + 1)
        local y = startY + (i - 1) * 2
        term.setBackgroundColor(btn.action == "logout" and colors.orange or colors.gray)
        term.setTextColor(colors.white)
        for x = x1, math.min(w, x1 + bw - 1) do
            term.setCursorPos(x, y)
            term.write(" ")
        end
        term.setCursorPos(x1 + 2, y)
        term.write(btn.text)
        buttons[i] = { x1 = x1, x2 = x1 + bw - 1, y = y, action = btn.action }
    end
end

-- === BOUCLE PRINCIPALE : une session par joueur ===
while true do
    local player = login.authenticate("Entre ton pseudo Minecraft :")
    local balance = bank.getBalance(player)
    drawScreen(player, balance)

    local playing = true
    while playing do
        local event, side, x, y = os.pullEvent("monitor_touch")
        if setupError then
            -- rien a faire, ecran d'erreur fixe
        else
            for _, btn in ipairs(buttons) do
                if x >= btn.x1 and x <= btn.x2 and y == btn.y then
                    if btn.action == "logout" then
                        playing = false
                    elseif btn.action == "deposit" then
                        local converted, newBal, err = depositAll(player)
                        if converted > 0 then
                            balance = newBal or balance
                            drawScreen(player, balance, converted .. " " .. CHIP_NAME .. "(s) convertis ! +" .. (converted * RATE), colors.lime)
                        else
                            drawScreen(player, balance, "Aucun " .. CHIP_NAME .. " trouve dans le guichet.", colors.orange)
                        end
                    else
                        local n = (btn.action == "w1" and 1) or (btn.action == "w5" and 5) or 10
                        local moved, newBal, err = withdraw(player, n, balance)
                        if newBal then balance = newBal end
                        if err and moved == 0 then
                            drawScreen(player, balance, err, colors.red)
                        elseif err then
                            drawScreen(player, balance, err, colors.orange)
                        else
                            drawScreen(player, balance, moved .. " " .. CHIP_NAME .. "(s) retires !", colors.lime)
                        end
                    end
                    break
                end
            end
        end
    end
end
